import Sprite from './render/Sprite';
import ballState from './global/ballState';
import Ball from './render/Ball';
import Plate from './render/Plate';
import Square from './render/Square';
import makeSquare from './utils/makeSquare';

const $ = document.querySelectorAll.bind(document);
const canvas = $("canvas")[0];
const bg_mp3 = $("#bgMp3")[0];
const active_mp3 = $("#activeMp3")[0];
bg_mp3.play();
const ctx = canvas.getContext("2d");
let animation = true;

// canvas实例
let plate = new Plate();
let ball = new Ball();
let square = new Square();
ball.x = plate.x + plate.w / 2;
ball.y = plate.y - ball.radius;
let groupArr = makeSquare(canvas,square, 5, 5, 50);


// 键盘事件
document.addEventListener('keydown', function (e) {
  e = e || window.event;
  if (e.keyCode === 37) {
    if (plate.x <= 0) {
      plate.x == 0;
      if (ball.state != ballState.RUN) {
        ball.x = plate.x + plate.w / 2;
      }
    } else {
      plate.x -= 40;
      if (ball.state != ballState.RUN) {
        ball.x -= 40;
      }
    }
  }
  if (e.keyCode === 39) {
    if (plate.x + plate.w >= canvas.width) {
      plate.x = canvas.width - plate.w;
      if (ball.state != ballState.RUN) {
        ball.x = plate.x + plate.w / 2;
      }
    } else {
      plate.x += 40;
      if (ball.state != ballState.RUN) {
        ball.x += 40;
      }
    }
  }
  if (e.keyCode == 32) {
    ball.flag = !ball.flag;
    if(ball.flag){
      ball.state = ballState.RUN
    }
  }
})

// canvas动画
requestAnimationFrame(next);
function next() {
  // 1.清除
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 2.移动
  ball.move();

  // 3.碰撞
  ball.collision(canvas,plate);
  groupArr.forEach((item,index)=>{
    let collision = item.collisionArc(ball);
    if(collision.collided){
      groupArr.splice(index,1);
      if(collision.position == 'y'){
        active_mp3.play();
        ball.vy = -ball.vy;
      }
      if(collision.position == 'x'){
        active_mp3.play();
        ball.vx = -ball.vx;
      }
    }
    collision = null;
  });

  // 4.绘制
  groupArr.forEach(item=>item.draw(ctx));
  plate.draw(ctx);
  ball.draw(ctx);
  if(!groupArr.length){
    win();
  }
  if(animation){
    requestAnimationFrame(next);
  }
}
function win(){

}
